import { ALL, Body, Get, Inject, Post, Query } from '@midwayjs/core';
import {
  CoolController,
  BaseController,
  CoolTag,
  TagTypes,
} from '@cool-midway/core';
import { OrderOrderEntity } from '../../entity/order';
import { OrderOrderService } from '../../service/order';
import { Context } from '@midwayjs/koa';
import moment = require('moment');
import { Between, Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';

/**
 * 订单信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderOrderEntity,
  service: OrderOrderService,
  pageQueryOp: {
    where: async ctx => {
      const { userId, roleId } = ctx.user;
      const { createTime, endTime } = ctx.request.body;
      const where: any = {};

      // 如果不是管理员，只能查询自己的订单
      if (roleId !== 1) {
        // 假设roleId为1是管理员
        where.userId = userId;
      }

      // 时间筛选
      if (createTime && endTime) {
        where.createTime = Between(new Date(createTime), new Date(endTime));
      }
      return where;
    },
  },
  listQueryOp: {
    where: async ctx => {},
  },
})
export class AppOrderOrderController extends BaseController {
  @Inject()
  orderOrderService: OrderOrderService;

  @Inject()
  ctx: Context;

  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;

  // 订单统计
  @Post('/statisticsByDate')
  async statisticsByDate(@Body(ALL) params: any) {
    // 验证日期格式
    const isValidDate = (dateStr: string) => {
      return moment(dateStr, 'YYYY-MM-DD').isValid();
    };

    const { startTime, endTime } = params;

    // 检查必填参数
    if (!startTime || !endTime) {
      return this.fail('请提供startDate和endDate参数');
    }

    // 验证日期有效性
    if (!isValidDate(startTime) || !isValidDate(endTime)) {
      return this.fail('日期格式无效，请使用YYYY-MM-DD格式');
    }

    // 处理时间范围
    const dateRange = [
      moment(startTime).startOf('day'), // 开始日期的00:00:00
      moment(endTime).endOf('day'), // 结束日期的23:59:59
    ];

    // 检查时间顺序
    if (dateRange[0].isAfter(dateRange[1])) {
      return this.fail('开始日期不能晚于结束日期');
    }

    // 调用服务层获取统计数据
    const result = await this.orderOrderService.statisticsByDate(
      dateRange[0].format('YYYY-MM-DD HH:mm:ss'),
      dateRange[1].format('YYYY-MM-DD HH:mm:ss')
    );

    return this.ok(result);
  }

  /**
   * 购买游戏币
   * @param packageId 套餐ID
   */
  /* 不需要登录 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/buy')
  async buyGameCoin(
    /* 套餐ID */
    @Body('packageId') packageId?: number,
    /*  */
    @Body('payAmount') payAmount?: number,
    /* 设备号 */
    @Body('deviceNo') deviceNo?: string,
    /* 微信OpenId */
    @Body('openId') openId?: string,
    // 支付方式 1：微信支付 2：支付宝支付
    @Body('payType') payType?: number
  ) { 
    const { ctx } = this;
    const userId = ctx?.user?.id || undefined; // 获取当前用户ID
    const order = await this.orderOrderService.buyGameCoin({
      packageId,
      payAmount,
      userId,
      deviceNo,
      openId,
      payType
    });
    return this.ok(order);
  }

  // 支付回调
  /* 不需要登录 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/callback')
  async callback(@Body() body: any) {
    const result = await this.orderOrderService.paySuccess(body);

    if (result === 'ok') {
      return {
        code: 'SUCCESS',
      };
    } else {
      return {
        code: 'FAIL',
      };
    }
  }
}
